package org.smart4j.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by Wangminze on 2016/12/10.
 * description: 属性文件工具类
 */
public class PropsUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtil.class);

    /**
      * author: Wangminze
      * date: 2016/12/10
      * description: 加载属性文件
     */
    public static Properties loadProps(String fileName){
        Properties props = null;
        InputStream istream = null;

        try {
            istream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            if ( istream == null ){
                throw new FileNotFoundException(fileName+"file is not found!");
            }
            props = new Properties();
            props.load(istream);
        }catch (IOException e){
            LOGGER.error("load properties file failure",e);
        }finally {
            if( istream != null ){
                try {
                    istream.close();
                }catch (IOException e){
                    LOGGER.error("close input stream failure",e);
                }
            }
        }

        return props;
    }

    /**
      * author: Wangminze
      * date: 2016/12/10
      * description: 获取字符型属性
      * @param props
      * @param key
      * @param defaultValue 指定返回默认值
      * @return 当props中没有指定的key时返回默认值
      */
    public static String getString(Properties props,String key,String defaultValue){
        if (props == null){
            return defaultValue;
        }
        String value = defaultValue;
        if (props.containsKey(key)){
            value = props.getProperty(key);
        }
        return value;
    }

    /**
     * author: Wangminze
     * date: 2016/12/10
     * description:
     * @param props
     * @param key
     * @param defaultValue 默认值
     * @return 当props中没有指定的key时返回默认值，有值但不是int类型时返回0
     */
    public static int getInt(Properties props,String key,int defaultValue){
        if (props == null){
            return defaultValue;
        }
        int value = defaultValue;
        if (props.containsKey(key)){
            value = CastUtil.cast2Int(props.getProperty(key),defaultValue);
        }
        return value;
    }

    /**
     * author: Wangminze
     * date: 2016/12/10
     * description:
     * @param props
     * @param key
     * @param defaultValue 默认值
     * @return 当props中没有指定的key时返回默认值，有值但不是boolean类型时返回false
     */
    public static boolean getBoolean(Properties props,String key,boolean defaultValue){
        if (props == null){
            return defaultValue;
        }
        boolean value = defaultValue;
        if (props.containsKey(key)){
            value = CastUtil.cast2Boolean(props.getProperty(key), defaultValue);
        }
        return value;
    }

}
